package cc.shacocloud.mirage.utils.comparator;

import cc.shacocloud.mirage.utils.annotation.AnnotatedElementUtils;
import jakarta.annotation.Priority;
import org.jetbrains.annotations.Nullable;

import java.lang.reflect.AnnotatedElement;
import java.util.Objects;

/**
 * {@code AnnotationOrderComparator} 是 {@link OrderComparator} 的扩展， 支持{@link  Ordered} 接口以及 {@link Order}
 * 和 {@link jakarta.annotation.Priority} 注释，其中 {@code Ordered} 实例提供的顺序值覆盖静态定义的注释值（如果有）。
 */
public class AnnotationOrderComparator extends OrderComparator {
    
    /**
     * {@code AnnotationOrderComparator} 的共享默认实例
     */
    public static final AnnotationOrderComparator INSTANCE = new AnnotationOrderComparator();
    
    
    /**
     * 此实现检查各种元素上的 {@link Order @Order} 或 {@link jakarta.annotation.Priority}，此外还检查超类中的 {@link Ordered}。
     */
    @Override
    @Nullable
    protected Integer findOrder(Object obj) {
        Integer order = super.findOrder(obj);
        if (Objects.nonNull(order)) {
            return order;
        }
        
        return findOrderFromAnnotation(obj);
    }
    
    @Nullable
    private Integer findOrderFromAnnotation(Object obj) {
        AnnotatedElement element = (obj instanceof AnnotatedElement ? (AnnotatedElement) obj : obj.getClass());
        
        Priority priority = AnnotatedElementUtils.getAnnotation(element, Priority.class);
        if (Objects.nonNull(priority)) {
            return priority.value();
        }
        
        Order order = AnnotatedElementUtils.getAnnotation(element, Order.class);
        if (Objects.nonNull(order)) {
            return order.value();
        }
        
        return null;
    }
    
}
